<?php
/**
 * Shopify异常订单
 * User: bgl
 * Date: 2023/2/7
 * Time: 9:35
 */

namespace App\Admin\Controllers\CustomerDelivery;

use App\Admin\Ajax\CustomerDelivery\ShopifyOrderExceptionAjax;
use App\Models\Shopify\ShopifyOrder;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Request;

class ShopifyOrderExceptionController extends AdminController{

    protected $title = 'shopify异常订单';

    protected $filters = [
        'start_date' => null,
        'end_date' => null,
        'order_id' => null,
        'sku' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->_paginator($query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['start_date'] = $this->filters['start_date'];
        $filtersBlade['end_date'] = $this->filters['end_date'];
        $filtersBlade['order_id'] = $this->filters['order_id'];
        $filtersBlade['sku'] = $this->filters['sku'];

        $downloadUrl = '/xqc/customer-delivery/shopify-order-exception-download?' . http_build_query(array_merge(Request::all(),['_export_' => true]));

        return view('customer-delivery.shopify-order-exception.index', compact('paginator','action','filtersBlade', 'downloadUrl'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        $query = ShopifyOrder::query()->where('erp_sync',3)->orderBy('id', 'DESC');

        foreach ($filters as $field => $filter){
            if(!$filter) continue;
            if($field == 'start_date'){
                $query->where('purchase_at', '>=', strtotime($filter.' 00:00:00'));
            }
            if($field == 'end_date'){
                $query->where('purchase_at', '<=', strtotime($filter.' 23:59:59'));
            }
            if($field == 'sku'){
                $query->whereHas('shopify_orders_items', function ($query) use($filter){
                    $query->where('sku', "%{$filter}%");
                });
            }
            if(in_array($field,['order_id'])){
                $query->where($field, $filter);
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new ShopifyOrderExceptionAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function download(){
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $query = $this->_initQuery($filters);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['订单号', '下单时间', '平台SKU', '品名','单位','状态'];
        RExcel::exportCsv('用户订单', function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::__getData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    private function __getData($re){
        foreach ($re as $row){
            $temp = [];
            $temp['order_id'] = $row->order_id;
            $temp['purchase_at'] = date('Y-m-d H:i:s',$row->purchase_at);
            yield $temp;
            foreach ($row->shopify_orders_items as $item){
                $temp = [];
                $temp['order_id'] = $row->order_id;
                $temp['purchase_at'] = date('Y-m-d H:i:s',$row->purchase_at);
                $temp['sku'] = $item->sku;
                $temp['name'] = $item->name;
                $temp['quantity'] = $item->quantity;
                $temp['erp_sync'] = ShopifyOrder::$_erpSync[$item->erp_sync];
                yield $temp;
            }
        }
    }
}
